/**
 * kl yy-ds @2021
 */
package com.cxps.server;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cxps.cloud.message.ApiResponse;
import com.cxps.cloud.utils.NumUtil;
import com.cxps.server.config.AlipayConfig;
import com.cxps.server.domain.BizContent;
import com.cxps.server.feign.FeignOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 测试类
 *
 * @author YouCai.Liu
 * @since 2021/11/9
 * ...
 */
@Slf4j
@RestController()
@RequestMapping("/pay")
public class IndexController {

    @Resource
    private FeignOrder feignOrder;

    /**
     * 支付宝异步通知回跳地址
     *
     * @return
     */
    @PostMapping("/notifyUrl")
    public String notifyUrl(HttpServletRequest request) {

        log.info("支付宝的异步通知===》》》");

        try {
            // 支付宝异步通知回调的参数集合
            Map<String, String> params = new HashMap<>();

            // 从请求中获取所有的参数集合，得到一个MAP集合
            Map<String, String[]> requestParams = request.getParameterMap();

            // 遍历从请求中获取所有的参数集合
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
                String name = iter.next();
                String[] values = requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                //乱码解决，这段代码在出现乱码时使用
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }

            // 调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGN_TYPE);
            if (signVerified) {
                // 签名验证通过，验证业务（没有一模一样的业务）

                // 商户需要验证该通知数据中的 out_trade_no 是否为商户系统中创建的订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

                // 去数据库查询支付宝回调参数里的 out_trade_no 这个对应的值，是不是我们业务的订单号

                // 以上逻辑全部验证通过，修改业务自身的逻辑：修改订单状态、减库存、加积分.....

                // 使用feign 调用订单服务，修改订单状态
//                feignOrder.updateOrderStatus(out_trade_no);

                return "success";
            } else {
                // 验证失败
                return "failure";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "failure";
        }
    }

    /**
     * 支付宝同步通知回跳地址
     *
     * @return
     */
    @GetMapping("/returnUrl")
    public void returnUrl(HttpServletResponse httpResponse) {
        /**
         * http://192.168.42.233/pay/returnUrl?
         * charset=UTF-8&
         * out_trade_no=20211109000001&
         * method=alipay.trade.page.pay.return&
         * total_amount=0.01&
         * sign=O9BACL69007WCJWP94NgwBPsUOauWX7NimUawl9YgP9m865SSWtZAQSkowUlFXdH6uTMIeBuGlTwusxMVPLM24LvwmoWIxwbBGJ1u11IpaX9AGgFkf7aWmktJ59wQwbJR8DAUexnuStkWoBo0/eXhoSZ2j3dws7Qk9nS5TpktS9aV1%2BD7gWjUlArSrGaB0qeeiDDBn8IM0HAjWH7v4jFoMBpHXkagtF2Fc3tcIxMqVT3UUAbBVYHt5JyKKPc9pirOzmbH7EEJFpTCwrx1EzRAibutHe1yYb8rvIkLZ335h6B/BQw0QA9svBJUCRqxrdgQ/8KzhFU6rUS2/VLmVTKw==&
         * trade_no=2021110922001473670501983537&
         * auth_app_id=2021000118648009&
         * version=1.0&
         * app_id=2021000118648009&
         * sign_type=RSA2&
         * seller_id=2088621957094122&
         * timestamp=2021-11-09+11%3A49%3A54
         */
        log.info("支付宝的同步通知===》》》");


        // 1、验证返回信息的准确性/正确性


        // 2、修改订单状态、减库存、积分

    }



    @Autowired
    private AlipayClient alipayClient;

    // 商户app id
    @Value("${cxps.app-id}")
    public String APP_ID;

    /**
     * 支付接口
     *
     * @return
     */
    @GetMapping("/do")
    public ApiResponse doPost(String productName, String totalPrice) {

        // 构建支付宝支付客户端
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL_DEV, APP_ID, AlipayConfig.RSA_PRIVATE_KEY,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGN_TYPE);

        // 创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

        // 在公共参数中设置回跳和通知地址
        alipayRequest.setReturnUrl(AlipayConfig.RETURN_URL);
        alipayRequest.setNotifyUrl(AlipayConfig.NOTIFY_URL);

        // 设置业务上下文
        String orderId = NumUtil.unique();
        BizContent bizContent = new BizContent(orderId, totalPrice, productName);
        bizContent.setTime_expire("2021-12-31 23:59:59");
        String bizCon = JSON.toJSONString(bizContent);

        // 填充业务参数
        alipayRequest.setBizContent(bizCon);

        // 支付宝返回 from 表单
        String form = "";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            log.error("调用SDK生成表单异常：" + e.getMessage(), e);
            return ApiResponse.fireError(e.getMessage());
        }
        return ApiResponse.fireSuccess(form);
    }
}
